import requestDic from "@/plugins/request/request_dic";
import { getRandomString } from "@/plugins/utils/common";
import axios from "axios";
import Setting from "../setting";

// 获取i国网CODE
export function getCode() {
  var sURL = "https://igw.isgcc.net:18081/connect/oauth2/authorize?"; // 本地、江西
  // let sURL = "https://igw.sgcc.com.cn/connect/oauth2/authorize?"; // 湖北
  sURL += `appid=${Setting.appid}`;
  sURL += "&redirect_uri=" + encodeURIComponent("zipapp://local.host/index.html");
  sURL += "&response_type=code";
  sURL += "&scope=SCOPE";
  sURL += "&state=STATE";
  sURL += `&agentid=${Setting.agentid}`;
  sURL += "#wechat_redirect";
  window.location.href = sURL;
}

// 从ISC获取ticket
export function getTicket(code) {
  var sURL = "";
  if (Setting.codeMode === "uapRelease") {
    // 生产环境
    sURL = "https://igw.isgcc.net:18443/proxy/getUserByIgwCode"; // 江西
    // sURL="https://id.sgcc.com.cn:10443/igwmobile/proxy/getUserByIgwCode"; // 湖北生产环境
  } else {
    // 测试环境
    sURL = "https://igw.isgcc.net:18443/identity/getAuthTicketByWechatCode";
  }
  var param = {
    CODE: code,
    appId: Setting.agentid,
  };
  return axios.post(sURL, JSON.stringify(param), {
    headers: { "Content-Type": "application/json;charset=UTF-8" },
  });
}

// 获取用户信息
export function getLoginUserInfo(ticket) {
  return requestDic({
    url: `/auth/igw/login`,
    method: "post",
    data: { ticket },
  });
}

// 退出登录接口
export function accountLoginOut() {
  return requestDic({
    url: `/auth/browser/logout`,
    method: "post",
  });
}

// 保持会话
export function keepsSessionHeart() {
  if (!sessionStorage.getItem("token") || sessionStorage.getItem("statusCode") == "401") {
    return;
  }
  return requestDic({
    url: `/session/heart?timeStamp=${new Date().getTime()}`,
    method: "get",
  });
}

// 重建会话
export function rebuildSession() {
  let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
  if (!sessionStorage.getItem("token") || !userInfo) return;
  let salt = getRandomString();
  let str = "" + userInfo.userId + userInfo.account + salt;
  let userSign = salt + SG_sm3encrypt(str);
  return requestDic({
    url: `/session/rebuild?userSign=${userSign}`,
    method: "get",
  });
}
